package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * ClassName: WmUserServiceImpl
 * Author:   WGG
 * Date:    2022-11-2022/11/16-15:22
 * Version: 1.0
 * Description:
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 自媒体用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.判断参数是否为空
        if (dto.getName()==null && dto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户是否存在
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser!=null){
            //使用md5加密密码 与查询的作比较
            String password = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
            if (password.equals(wmUser.getPassword())){
                //如果相等，将token和wmUser存入map集合并返回
                HashMap<String, Object> map = new HashMap<>();
                //隐藏密码
                wmUser.setPassword("");
                //隐藏盐
                wmUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
                map.put("user", wmUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }
}
